<template>
	<BasicDrawer v-bind="$attrs" @register="registerDrawer" width="90%" showFooter destroyOnClose title="编辑大团信息"
		:width="900" @ok="handleSubmit">
		<!-- 报名用户信息 -->
		<BasicForm @register="registerForm">

			<template #earlyBirdPrice="{ model, field }">
				<a-row>
					<!-- 早鸟价 -->
					<div style="overflow:auto;width:100%">
						<BasicTable style="white-space:nowrap" @register="registerTableEarlyBirdPrice"
							:columns="earlyBirdPriceColumns" :dataSource="earlyBirdPrice" :pagination="false">
							<!-- :dropDownActions="getDropDownAction(record)"  @edit-change="onEditChange"-->
							<template #action="{ record, column }">
								<TableAction :actions="createActions1(record, column)" />
							</template>
						</BasicTable>
					</div>
				</a-row>
			</template>
			<template #selectTravelCalendar="{ model, field }">
				<a-row>
					<!-- 日程管理：这里显示表格 用户选择的出发日期-->
					<a-button type="primary" @click="handleAdd(4)" preIcon="ant-design:plus-outlined"> 新增用户可选日程</a-button>
					<div style="overflow:auto;width:100%">
						<BasicTable style="white-space:nowrap" @register="registerAlternativeJounerys"
							:columns="alternativeColumns" :dataSource="alternativeJounerys" :pagination="false">
							<!-- :dropDownActions="getDropDownAction(record)"  @edit-change="onEditChange"-->
							<template #action="{ record, column }">
								<TableAction :actions="createActions5(record, column)" />
							</template>
						</BasicTable>
					</div>
				</a-row>
			</template>
			<template #ScheduleSelection="{ model, field }">
				<a-row>
					<!-- 日程管理：这里显示表格  确定的出发日期-->
					<a-button type="primary" @click="handleAdd(1)" preIcon="ant-design:plus-outlined"> 新增确定出发日程</a-button>
					<div style="overflow:auto;width:100%">
						<BasicTable style="white-space:nowrap" @register="registerJounerys" :columns="usersColumns"
							:dataSource="jounerys" :pagination="false">
							<!-- :dropDownActions="getDropDownAction(record)"  @edit-change="onEditChange"-->
							<template #action="{ record, column }">
								<TableAction :actions="createActions2(record, column)" />
							</template>
						</BasicTable>
					</div>
				</a-row>
			</template>

			<template #TieredPrice="{ model, field }">
				<a-row>
					<a-button type="primary" @click="handleAdd(2)" preIcon="ant-design:plus-outlined"> 新增</a-button>
					<div style="overflow:auto;width:100%">
						<!-- @edit-end="handleEditEnd2" @edit-cancel="handleEditCancel2"
							:beforeEditSubmit="beforeEditSubmit2" -->
						<BasicTable @register="registerTieredPrices" style="white-space:nowrap"
							:columns="tieredPricingColumns" :dataSource="tieredPrices" :pagination="false">
							<template #action="{ record, column }">
								<TableAction :actions="createActions3(record, column)" />
							</template>
						</BasicTable>
					</div>
				</a-row>
			</template>
			<template #PayPrices="{ model, field }">
				<a-row>
					<a-button type="primary" @click="handleAdd(3)" preIcon="ant-design:plus-outlined"> 新增</a-button>
					<div style="overflow:auto;width:100%">
						<!-- @edit-end="handleEditEnd3" @edit-cancel="handleEditCancel3"
							:beforeEditSubmit="beforeEditSubmit3" -->
						<BasicTable @register="registerPayPrices" style="white-space:nowrap" :columns="payPriceColumns"
							:dataSource="payPrices" :pagination="false">
							<template #action="{ record, column }">
								<TableAction :actions="createActions4(record, column)" />
							</template>
						</BasicTable>
					</div>
				</a-row>
			</template>

		</BasicForm>
	</BasicDrawer>
</template>

<script lang="ts" setup>
	import { ref, computed, unref, watchEffect, toRaw, onUnmounted, onBeforeUnmount } from 'vue';
	import { useUserStoreWithOut } from '/@/store/modules/user';
	import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
	import { BasicForm, useForm } from '/@/components/Form/index';
	import { saveOrUpdate } from '../../BsTravelgroupTravelistgroup.api';
	import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table/index';
	import { formSchema, usersColumns, pdtsColumns, tieredPricingColumns, payPriceColumns, earlyBirdPriceColumns, alternativeColumns } from './index.data';
	import { render, formattingMin, formattingDay } from '/@/utils/common/renderUtils';
	import { useMessage } from '/@/hooks/web/useMessage';
	import { cloneDeep } from 'lodash-es';
	// import { editOrderSite } from './index.api';
	// Emits声明
	const emit = defineEmits(['register', 'submit', 'entryType']);
	const isUpdate = ref(true);
	const isCopy = ref(true);
	const earlyBirdPrice = ref([] as Array<any>)
	const jounerys = ref([] as Array<any>)
	const tieredPrices = ref([] as Array<any>)
	const payPrices = ref([] as Array<any>)
	const alternativeJounerys = ref([] as Array<any>)

	const userInfo = computed(() => {
		const userStore = useUserStoreWithOut();
		return userStore.getUserInfo;
	});
	onBeforeUnmount(() => {

		console.log("---------->182-------->")
	})

	//表单配置
	const [registerForm, { setProps, resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
		//labelWidth: 150,
		schemas: formSchema,
		showActionButtonGroup: false,
		baseColProps: { span: 12 },
		labelWidth: 120
	});
	//表单赋值
	const [registerDrawer, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
		//重置表单
		await resetFields();
		setDrawerProps({
			confirmLoading: false,
			showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter,
			// canFullscreen: false
		});
		isUpdate.value = !!data?.isUpdate;
		isCopy.value = !!data?.isCopy;
		// 	//表单赋值
		//早鸟价，出发日期，阶梯价，优惠价 
		if (isUpdate.value || data.isCopy) {
			console.log(data.record)
			if (data.record.isEarly == 1) {
				earlyBirdPrice.value = []
				earlyBirdPrice.value.push(JSON.parse(data.record.earlyBirdPrice))
				console.log(earlyBirdPrice.value)
				setEarlyBirdPriceTable(earlyBirdPrice.value);
			} else {
				earlyBirdPrice.value = [{ activeprice: '', priceexpiretime: '', sortnum: '', enddate: '', startdate: '' }]
			}

			// 用户可选择日程
			if (data.record.userSelectDay) {
				alternativeJounerys.value = JSON.parse(data.record.userSelectDay)
			} else {
				alternativeJounerys.value = []
			}
			setDayAlternativeTableDate(alternativeJounerys.value)
			
			console.log(data.record.userSelectDay,data.record.travelcalendar)
			
			//已确定出发日程
			if (data.record.travelcalendar) {
				jounerys.value = JSON.parse(data.record.travelcalendar)
			}else{
				jounerys.value = []
			}
			setDayTableDate(jounerys.value)

			//阶梯价格
			if (data.record.stepprice) {
				tieredPrices.value = JSON.parse(data.record.stepprice)
			} else {
				tieredPrices.value = []
			}
			setTableDataTieredPrice(tieredPrices.value)

		
			//支付优惠价格
			if (data.record.payPrice) {
				payPrices.value = JSON.parse(data.record.payPrice)
			}else{
				payPrices.value =[]
			}
			setTableDataPayPrice(payPrices.value)

			await setFieldsValue({
				...data.record,
			});
		} else {
			earlyBirdPrice.value = [{ activeprice: '', priceexpiretime: '', sortnum: '', enddate: '', startdate: '' }]
		}

		setProps({ disabled: !data?.showFooter })
	});


	const { createMessage } = useMessage();
	function handleAdd(i) {
		currentEditKeyRef.value = '';
		if (i == 1) {
			let a = { soDay: '', price: '', id: jounerys.value.length + 1 };
			jounerys.value.push(a)
			setDayTableDate(jounerys.value)

		} else if (i == 2) {
			let tieredPrice = { price: '', minNum: '', maxNum: '', id: tieredPrices.value.length + 1 }
			tieredPrices.value.push(tieredPrice)
			setTableDataTieredPrice(tieredPrices.value)
		} else if (i == 3) {
			let payPrice = { price: '', minNum: '', maxNum: '', id: payPrices.value.length + 1 }
			payPrices.value.push(payPrice)
			setTableDataPayPrice(payPrices.value)
		} else if (i == 4) {
			let a = { soDay: '', toDay: '', price: '', id: alternativeJounerys.value.length + 1 };
			alternativeJounerys.value.push(a)
			setDayAlternativeTableDate(alternativeJounerys.value)
		}
	}

	//设置标题
	// const title = computed(() => (!unref(isUpdate) ? '编辑检测信息' : '编辑'));
	//表单提交事件
	async function handleSubmit(v) {
		try {
			//这里提交表单到上级页面处理
			let values = await validate();
			values.payPrice = JSON.stringify(payPrices.value)
			if (payPrices.value.length == 0) {
				return createMessage.error({
					content: '请先设置支付优惠价格',
					key: 'payPrices',
					duration: 2,
				});
			}
			values.stepprice = JSON.stringify(tieredPrices.value)
			if (tieredPrices.value.length == 0) {
				return createMessage.error({
					content: '请先设置成团阶梯价格',
					key: 'tieredPrices',
					duration: 2,
				});
			}
			//用户可选择的日历行程
			values.travelcalendar = JSON.stringify(alternativeJounerys.value)
			if (alternativeJounerys.value.length == 0) {
				return createMessage.error({
					content: '请先设置用户可选择的日历行程',
					key: 'alternativeJounerys',
					duration: 2,
				});
			}
			//早鸟价
			if (values.isEarly == 1) {
				//早鸟价
				earlyBirdPrice.value.enddate = earlyBirdPrice.value.priceexpiretime
				values.earlyBirdPrice = JSON.stringify(earlyBirdPrice.value)
				if(values.earlyBirdPrice.indexOf("[")>-1){
					values.earlyBirdPrice = JSON.stringify(earlyBirdPrice.value[0])
				}
			} /* else {
				earlyBirdPrice.value.enddate = getCurrentDateTime();
				earlyBirdPrice.value.startdate = '2099-01-01 00:00:00'
				//无早鸟价
				earlyBirdPrice.value.sortnum = -1
				earlyBirdPrice.value.activeprice = -1
				earlyBirdPrice.value.priceexpiretime = getCurrentDateTime();
				values.earlyBirdPrice = JSON.stringify(earlyBirdPrice.value)
			} */
			if (values.xjSelect == 1) {
				values.enddateStr = '2026-01-01 00:00:00';
			}
			if (values.sjSelect == 1) {
				values.startdateStr = getCurrentDateTime();
			}

			//将上下架时间、早鸟价都存入ext

			console.log('-----')
			console.log('-----')
			console.log(values)
			values.travelMarkDays = JSON.stringify(jounerys.value)
			console.log('-----')
			console.log('-----')
			await saveOrUpdate(values, isUpdate.value,isCopy.value);

			//提交后清空
			earlyBirdPrice.value = [{ activeprice: '', priceexpiretime: '', sortnum: '', enddate: '', startdate: '' }]
			jounerys.value = []
			tieredPrices.value = []
			payPrices.value = []
			alternativeJounerys.value = []

			//这里直接提交
			closeDrawer();
			//刷新列表
			emit('success');
			setDrawerProps({ confirmLoading: true });
			//刷新列表
		} finally {
			setDrawerProps({ confirmLoading: false });
		}
	}
	function getCurrentDateTime() {
		var now = new Date();
		var year = now.getFullYear();
		var month = now.getMonth() + 1; // 月份是从0开始的，所以需要+1
		var day = now.getDate();
		var hours = now.getHours();
		var minutes = now.getMinutes();
		var seconds = now.getSeconds() //秒
		// 如果需要补零，可以使用以下代码
		month = month < 10 ? '0' + month : month;
		day = day < 10 ? '0' + day : day;
		hours = hours < 10 ? '0' + hours : hours;
		minutes = minutes < 10 ? '0' + minutes : minutes;

		return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
	}

	function createActions1(record : EditRecordRow, column : BasicColumn) : ActionItem[] {
		if (!record.editable) {
			return [
				{
					label: '编辑',
					disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
					onClick: handleEdit.bind(null, record, 1),
				},
				/* {
					label: '删除',
					popConfirm: {
						title: '是否确认删除',
						confirm: handleDelete.bind(null, record, 1),
						placement: 'topLeft',
					}
				}, */
			];
		}
		return [
			{
				label: '保存',
				onClick: handleSave.bind(null, record, column, 1),
			},
			{
				label: '取消',
				popConfirm: {
					title: '是否取消编辑',
					confirm: handleCancel.bind(null, record, column, 1),
				},
			},
		];
	}
	function createActions2(record : EditRecordRow, column : BasicColumn) : ActionItem[] {
		if (!record.editable) {
			return [
				{
					label: '编辑',
					disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
					onClick: handleEdit.bind(null, record, 2),
				},
				{
					label: '删除',
					popConfirm: {
						title: '是否确认删除',
						confirm: handleDelete.bind(null, record, 2),
						placement: 'topLeft',
					}
				},
			];
		}
		return [
			{
				label: '保存',
				onClick: handleSave.bind(null, record, column, 2),
			},
			{
				label: '取消',
				popConfirm: {
					title: '是否取消编辑',
					confirm: handleCancel.bind(null, record, column, 2),
				},
			},
		];
	}
	function createActions3(record : EditRecordRow, column : BasicColumn) : ActionItem[] {
		if (!record.editable) {
			return [
				{
					label: '编辑',
					disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
					onClick: handleEdit.bind(null, record, 3),
				},
				{
					label: '删除',
					popConfirm: {
						title: '是否确认删除',
						confirm: handleDelete.bind(null, record, 3),
						placement: 'topLeft',
					}
				},
			];
		}
		return [
			{
				label: '保存',
				onClick: handleSave.bind(null, record, column, 3),
			},
			{
				label: '取消',
				popConfirm: {
					title: '是否取消编辑',
					confirm: handleCancel.bind(null, record, column, 3),
				},
			},
		];
	}
	function createActions4(record : EditRecordRow, column : BasicColumn) : ActionItem[] {
		if (!record.editable) {
			return [
				{
					label: '编辑',
					disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
					onClick: handleEdit.bind(null, record, 4),
				},
				{
					label: '删除',
					popConfirm: {
						title: '是否确认删除',
						confirm: handleDelete.bind(null, record, 4),
						placement: 'topLeft',
					}
				},
			];
		}
		return [
			{
				label: '保存',
				onClick: handleSave.bind(null, record, column, 4),
			},
			{
				label: '取消',
				popConfirm: {
					title: '是否取消编辑',
					confirm: handleCancel.bind(null, record, column, 4),
				},
			},
		];
	}

	function createActions5(record : EditRecordRow, column : BasicColumn) : ActionItem[] {
		if (!record.editable) {
			return [
				{
					label: '编辑',
					disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
					onClick: handleEdit.bind(null, record, 5),
				},
				{
					label: '删除',
					popConfirm: {
						title: '是否确认删除',
						confirm: handleDelete.bind(null, record, 5),
						placement: 'topLeft',
					}
				},
			];
		}
		return [
			{
				label: '保存',
				onClick: handleSave.bind(null, record, column, 5),
			},
			{
				label: '取消',
				popConfirm: {
					title: '是否取消编辑',
					confirm: handleCancel.bind(null, record, column, 5),
				},
			},
		];
	}
	const currentEditKeyRef = ref('');
	const [registerTableEarlyBirdPrice, { setTableData: setEarlyBirdPriceTable }] = useTable({
		api: getEarlyBirdPriceData(),
		columns: earlyBirdPriceColumns,
		showIndexColumn: false,
		showTableSetting: true,
		tableSetting: { fullScreen: false },
		actionColumn: {
			width: 160,
			title: '操作',
			dataIndex: 'action',
			slots: { customRender: 'action' },
		},
	});


	function getEarlyBirdPriceData() {
		earlyBirdPrice.value = [{ sortnum: '', activeprice: '', priceexpiretime: '', enddate: '', startdate: '' }]
		console.log("---------->472------>", earlyBirdPrice.value)
		return earlyBirdPrice
	}

	function handleEdit(record : EditRecordRow, i) {
		currentEditKeyRef.value = record.key;
		record.onEdit?.(true);
	}


	function handleDelete(record : EditRecordRow, k) {

		if (k == 2) {

			let jss = jounerys.value
			for (let i = 0; i < jss.length; i++) {
				if (jss[i].id == record.id) {
					jounerys.value.splice(i, 1)
				}
			}

			//id重新赋值
			for (let i = 0; i < jounerys.value.length; i++) {
				jounerys.value[i].id = i + 1;
			}
			setDayTableDate(jounerys.value)
		} else if (k == 3) {
			let jss = tieredPrices.value
			for (let i = 0; i < jss.length; i++) {
				if (jss[i].id == record.id) {
					tieredPrices.value.splice(i, 1)
				}
			}

			//id重新赋值
			for (let i = 0; i < tieredPrices.value.length; i++) {
				tieredPrices.value[i].id = i + 1;
			}
			setTableDataTieredPrice(tieredPrices.value)
		} else if (k == 4) {
			let jss = payPrices.value
			for (let i = 0; i < jss.length; i++) {
				if (jss[i].id == record.id) {
					payPrices.value.splice(i, 1)
				}
			}

			//id重新赋值
			for (let i = 0; i < payPrices.value.length; i++) {
				payPrices.value[i].id = i + 1;
			}
			setTableDataPayPrice(payPrices.value)

		} else if (k == 5) {
			let jss = alternativeJounerys.value
			for (let i = 0; i < jss.length; i++) {
				if (jss[i].id == record.id) {
					alternativeJounerys.value.splice(i, 1)
				}
			}
			//id重新赋值
			for (let i = 0; i < alternativeJounerys.value.length; i++) {
				alternativeJounerys.value[i].id = i + 1;
			}
			setDayAlternativeTableDate(alternativeJounerys.value)

		}

	}

	function handleCancel(record : EditRecordRow, i) {
		currentEditKeyRef.value = '';
		record.onEdit?.(false, false);
	}

	async function handleSave(record : EditRecordRow, row, i) {
		// 校验
		createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
		const valid = await record.onValid?.();
		if (valid) {
			try {
				const data = cloneDeep(record.editValueRefs);
				//TODO 此处将数据提交给服务器保存
				if (i == 1) {
					earlyBirdPrice.value = data
				} else if (i == 2) {
					data.id = jounerys.value.length;
					jounerys.value[record.id - 1] = data
				} else if (i == 3) {
					data.id = tieredPrices.value.length;
					tieredPrices.value[record.id - 1] = data
				} else if (i == 4) {
					data.id = payPrices.value.length;
					payPrices.value[record.id - 1] = data
				} else if (i == 5) {
					data.id = alternativeJounerys.value.length;
					alternativeJounerys.value[record.id - 1] = data
				}
				// 保存之后提交编辑状态
				const pass = await record.onEdit?.(false, true);
				if (pass) {
					currentEditKeyRef.value = '';
				}
				createMessage.success({ content: '数据已保存', key: 'saving' });
			} catch (error) {
				console.log(error)
				createMessage.error({ content: '保存失败', key: 'saving' });
			}
		} else {
			createMessage.error({ content: '请填写正确的数据', key: 'saving' });
		}
	}

	const [registerAlternativeJounerys, { setTableData: setDayAlternativeTableDate }] = useTable({
		api: getAlternativeJounerysData(),
		columns: alternativeColumns,
		showIndexColumn: false,
		showTableSetting: true,
		tableSetting: { fullScreen: true },
		actionColumn: {
			width: 160,
			title: '操作',
			dataIndex: 'action',
			slots: { customRender: 'action' },
		},
	});

	function getAlternativeJounerysData() {

		return []
	}

	const [registerJounerys, { setTableData: setDayTableDate }] = useTable({
		api: getJounerysData(),
		columns: usersColumns,
		showIndexColumn: false,
		showTableSetting: true,
		tableSetting: { fullScreen: true },
		actionColumn: {
			width: 160,
			title: '操作',
			dataIndex: 'action',
			slots: { customRender: 'action' },
		},
	});

	function getJounerysData() {
		return []
	}

	const [registerPayPrices, { setTableData: setTableDataPayPrice }] = useTable({
		title: '优惠价格',
		titleHelpMessage: ['支付优惠价格管理'],
		api: getPayPricesData(),
		columns: payPriceColumns,
		showIndexColumn: false,
		showTableSetting: true,
		tableSetting: { fullScreen: true },
		actionColumn: {
			width: 160,
			title: '操作',
			dataIndex: 'action',
			slots: { customRender: 'action' },
		},
	});
	function getPayPricesData() {

		return []
	}

	const [registerTieredPrices, { setTableData: setTableDataTieredPrice }] = useTable({
		title: '阶梯价格',
		titleHelpMessage: ['成团阶梯价格管理'],
		api: getTieredPricesData(),
		columns: tieredPricingColumns,
		showIndexColumn: false,
		showTableSetting: true,
		tableSetting: { fullScreen: true },
		actionColumn: {
			width: 160,
			title: '操作',
			dataIndex: 'action',
			slots: { customRender: 'action' },
		},
	});
	function getTieredPricesData() {

		return []
	}
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
	:deep(.ant-input-number) {
		width: 100%
	}

	:deep(.ant-calendar-picker) {
		width: 100%
	}

	.margin-l-th {
		margin-left: 10px;
	}

	.colorRed {
		color: red;
	}

	.title {
		font-weight: 500;
	}

	h3 {
		font-weight: 700;
	}
</style>